### Program Name
TARGET=bin/IO_int

### Linker Script
LDFILE = Targets/fire/STM32F429NIHx_FLASH.ld

### Device
DEVICE = STM32F429xx

### Toolchain directory
TOOLCHAIN_DIR = /usr/gcc-arm-none-eabi-10.3-2021.10/bin/

CC = $(TOOLCHAIN_DIR)arm-none-eabi-gcc
LD = $(TOOLCHAIN_DIR)arm-none-eabi-gcc
AR = $(TOOLCHAIN_DIR)arm-none-eabi-ar
AS = $(TOOLCHAIN_DIR)arm-none-eabi-as
CP = $(TOOLCHAIN_DIR)arm-none-eabi-objcopy
OD = $(TOOLCHAIN_DIR)arm-none-eabi-objdump
SZ = $(TOOLCHAIN_DIR)arm-none-eabi-size
OPENOCD = /mnt/d/xpack-openocd-0.11.0-3/bin/openocd.exe

### Includes
CMSIS_INC_DIR = Drivers/CMSIS/Include
CMSIS_ST_INC_DIR = Drivers/CMSIS/Device/ST/STM32F4xx/Include
HAL_INC_DIR = Drivers/STM32F4xx_HAL_Driver/Inc
USER_INC = inc

INC = -I$(USER_INC) -I$(CMSIS_INC_DIR) -I$(CMSIS_ST_INC_DIR) -I$(HAL_INC_DIR) 

### Sources
CMSIS_SYS_SRC = Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/system_stm32f4xx.c 
CMSIS_START_SRC = Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/startup_stm32f429xx.s
USER_SRC = src/IO_int.c src/fire_led.c src/stm32f4xx_it.c
HAL_SRC = Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c \
		Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c \
		Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c \
		Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c \
	 	Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c 

SRC_c = $(CMSIS_SYS_SRC) $(USER_SRC) $(HAL_SRC)

OBJ = $(patsubst %.c, obj/%.o, $(notdir $(SRC_c))) \
		$(patsubst %.s, obj/%.o, $(notdir $(CMSIS_START_SRC)))
VPATH = $(sort $(dir $(SRC_c))) $(dir $(CMSIS_START_SRC))

### CFLAGS
CFLAGS = $(INC) -D$(DEVICE) -mcpu=cortex-m4 -mthumb -g -T$(LDFILE) -Wl,-Map=$(TARGET).map -specs=nosys.specs

### Rules
$(TARGET).elf: $(OBJ)
	$(LD) $(CFLAGS) -o $@ $^
	$(CP) -O binary $(TARGET).elf $(TARGET).bin

obj/%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<
obj/%.o: %.s
	$(CC) $(CFLAGS) -c -o $@ $<

.PHONY: clean flash da help
clean:
	rm -f obj/*.o $(TARGET).elf $(TARGET).bin $(TARGET).map
da:
	$(OD) -d $(TARGET).elf > $(TARGET).s
flash:
# For windows wsl2. Need usd driver installed under win first.
# Currently using Winusb installed by Zadig. This prevents the J-link being used by SEGGER flasher.
	$(OPENOCD) -f Targets/fire/openocd_jlink_swd.cfg -f Targets/fire/stm32f4x.cfg -c "program $(TARGET).elf verify reset exit"
jtag:
	$(OPENOCD) -f Targets/fire/openocd_jlink_swd.cfg -f Targets/fire/stm32f4x.cfg -c "targets" -c "shutdown"
help:
	@echo "$(OPENOCD) -f Targets/fire/openocd_jlink_swd.cfg -f Targets/fire/stm32f4x.cfg"
	@echo "$(TOOLCHAIN_DIR)arm-none-eabi-gdb -ex \"target remote :3333\" $(TARGET).elf"